package com.summer.thread;

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicTest {

	
	public static void main(String[] args) {
		Counter1 c1 = new Counter1();
		c1.doTest();
		c1.doTest();
		c1.doTest();
		c1.doTest();
		c1.doTest();
		c1.doTest();
		c1.doTest();
		Counter2 c2 = new Counter2();
		c2.doTest();
		c2.doTest();
		c2.doTest();
		c2.doTest();
		c2.doTest();
		c2.doTest();
		c2.doTest();
	}
	
	
	public static class Counter1{
		private int counter=0;
		private volatile static int nub=0;
		private long time;
		public void doTest(){
			if(nub==0){
				time = System.currentTimeMillis();
			}
			nub++;
			new Thread(new Runnable(){
				@Override
				public void run() {
					int index = 0;
					while(index<100000){
						increase();
						index++;
					}
					nub--;
					if(nub==0){
						time = System.currentTimeMillis()-time;
						System.out.println("use time::"+time);
						System.out.println("counter::"+counter);
					}
				}
			}).start();
		}
		
		public int increase(){
			synchronized (this) {
				counter = counter + 1;
				return counter;
			}
		}
		public int decrease(){
			counter = counter - 1;
			return counter;
		}
	}
	
	public static class Counter2{
		private AtomicInteger counter = new AtomicInteger(0);
		private volatile static int nub=0;
		private long time;
		public void doTest(){
			if(nub==0){
				time = System.currentTimeMillis();
			}
			nub++;
			new Thread(new Runnable(){
				@Override
				public void run() {
					int index = 0;
					while(index<100000){
						increase();
						index++;
					}
					nub--;
					if(nub==0){
						time = System.currentTimeMillis()-time;
						System.out.println("Atomic use time::"+time);
						System.out.println("Atomic counter ::"+counter);
					}
				}
			}).start();
		}
		
		public int increase(){
			return counter.incrementAndGet(); 
		}
		public int decrease(){
			return counter.decrementAndGet();
		}
	}
	
}
